package net.jxvtc.eshop.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.log4j.Logger;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

/**
 * 要实现单例模式，保证全局只有一个数据库连接池
 */
public class DataSourceUtils {
	static Logger log = Logger.getLogger(DataSourceUtils.class);

	private static DruidDataSource dataSource = null;
	static {

		try {
			Properties properties = loadPropertiesFile("druid.properties");

			// dataSource=new DruidDataSource();
			// dataSource.setDriverClassName("com.mysql.jdbc.Driver");
			// dataSource.setUsername("root"); dataSource.setPassword("123456");
			// dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/itcaststore");
			// dataSource.setInitialSize(5);
			// dataSource.setMinIdle(1);
			// dataSource.setMaxActive(10); // 启用监控统计功能
			// dataSource.setFilters("stat");// for mysql
			// dataSource.setPoolPreparedStatements(false);
			dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
		} catch (Exception e) {
			log.error("获取配置失败");
		}
	}

	public static DataSource getDataSource() {
		return dataSource;
	}

	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

	public static Connection getConnection() throws SQLException {
		Connection conn = tl.get();
		if (conn == null) {
			conn = dataSource.getConnection();
			tl.set(conn);
		}
		return conn;
	}

	public static void startTransaction() throws SQLException {
		Connection conn = tl.get();
		if (conn != null) {
			conn.setAutoCommit(false);
		}
	}

	public static void rollback() throws SQLException {
		Connection conn = tl.get();
		if (conn != null) {
			conn.rollback();
		}
	}

	public static void releaseAndCloseConnection() throws SQLException {
		Connection conn = tl.get();
		if (conn != null) {
			conn.commit();
			tl.remove();
			conn.close();
		}
	}

	private static Properties loadPropertiesFile(String fullFile) {
	

		InputStream inputStream = null;
		Properties p = null;
		try {
			inputStream = DataSourceUtils.class.getResourceAsStream("/"+fullFile);
			p = new Properties();
			p.load(inputStream);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != inputStream) {
					inputStream.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return p;
	}
}